﻿using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace FrameworkCore.Extensions;

public class CustomDateTimeConverter : JsonConverter<DateTime>
{
    private readonly string[] formats = new[]
    {
        "yyyy-MM-dd HH:mm:ss", // 包含秒的格式
        "yyyy-MM-dd HH:mm"      // 不包含秒的格式
    };

    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var dateString = reader.GetString();
        return DateTime.ParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
    }
}
